package favorGenericTypes;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: Georgiana.Scarlat
 * Date: 8/30/12
 * Time: 9:48 AM
 *
 */
public class LamePriorityQueue {
    private Comparable[] objects;
    private static final int INITIAL_CAPACITY = 15;
    int size;

    public LamePriorityQueue() {
        objects = new Comparable[INITIAL_CAPACITY];
    }

    public void push(Comparable object){

        extendCapacityIfNecessary();

        int index = getIndexInWhichToInsert(object);

        makeSpaceForInsertion(index);

        objects[index] = object;

        size++;

    }

    private void makeSpaceForInsertion(int index) {

        System.arraycopy(objects, index, objects, index + 1, size - index);
    }

    private int getIndexInWhichToInsert(Comparable object) {
        int index;
        for(index = 0;index<size;index++){
            if(object.compareTo(objects[index]) < 0)
                return index;
        }


        return index;
    }

    public Comparable pop()  {
        if(size == 0)
            throw new UnsupportedOperationException("Can't pop from empty priority queue.");
        Comparable result = objects[--size];
        objects[size] = null;
        return result;
    }

    private void extendCapacityIfNecessary() {

        if(size == objects.length){
            objects = Arrays.copyOf(objects, size * 2);
        }
    }



    @Override
    public String toString() {
        return "LamePriorityQueue{" +
                "objects=" + (objects == null ? null : Arrays.asList(Arrays.copyOf(objects,size))) +
                '}';
    }

    public static void main(String[] args) {

        LamePriorityQueue priorityQueue = getSomePrioriryQueue();

        System.out.println(priorityQueue);

        //priorityQueue.push("ana");
    }



    private static LamePriorityQueue getSomePrioriryQueue() {

        LamePriorityQueue priorityQueue = new LamePriorityQueue();

        priorityQueue.push(1);
        priorityQueue.push(10);
        priorityQueue.push(4);
        priorityQueue.push(0);
        priorityQueue.push(11);

        return priorityQueue;
    }
}
